import { call, put, takeLatest } from 'redux-saga/effects';
import { message } from 'antd';

import api from '../../../api';
import flat from '../../../flat';
import { setToken, setApiUrl, setServiceUrl } from '../../../config';

import actionCreators from './actionCreators';
import { GET_SYSTEM_SAGA } from './actionTypes';

/**
 * 获取系统配置信息
 * @return
 */
function* getConfig() {
    const config = yield call(api.system.getConfig);
    const {
        statusInfo: { status },
    } = config;
    if (status === 200) {
        delete config.statusInfo;
        const entities = flat.system(config).entities;
        const { API_ALIAS, SERVICE_ALIAS, VGIMAP_ALIAS } = window.TDT_CONFIG;
        const apiProject = entities.projects[API_ALIAS];
        const serviceProject = entities.projects[SERVICE_ALIAS];
        const mapProject = entities.projects[VGIMAP_ALIAS];

        const { url: apiUrl } = apiProject;
        const { url: serviceUrl } = serviceProject;
        const { token } = mapProject;

        if (!apiProject) {
            message.error('api项目信息未配置！');
            return;
        }

        if (!mapProject) {
            message.error('地图网站项目信息未配置！');
            return;
        }

        if (!apiUrl || !token) {
            message.error('api项目未配置域名!');
            return;
        }
        if (!token) {
            message.error('地图网站项目未配置token!');
            return;
        }

        setApiUrl(apiUrl);
        setServiceUrl(serviceUrl);
        setToken(token);
        yield put(actionCreators.add(entities));
    }
}

export default function* saga() {
    yield takeLatest(GET_SYSTEM_SAGA, getConfig);
}
